import json

import requests
from utils.read import base_data
from utils.log_util import logger
from utils.response_util import process_response

api_root_url = base_data.read_ini()['host']['api_sti_url']
class RestClient:
    def __init__(self):
        self.api_root_url = api_root_url
        #加入会话机制
        self.session = requests.session()

    def get(self, url, **kwargs):
        return self.request(url, "GET" ,**kwargs)

    def post(self, url, **kwargs):
        return self.request(url, "POST", **kwargs)

    def put(self, url, **kwargs):
        return self.request(url, "PUT", **kwargs)

    def delete(self, url, **kwargs):
        return self.request(url, "DELETE", **kwargs)

    def request(self, url, method, **kwargs):
        self.request_log(url, method, **kwargs)
        if method == "GET":
            return self.session.get(self.api_root_url + url, **kwargs)
        if method == "POST":
            return self.session.post(self.api_root_url + url, **kwargs)
        if method == "PUT":
            return self.session.put(self.api_root_url + url, **kwargs)
        if method == "DELETE":
            return self.session.delete(self.api_root_url + url, **kwargs)

        """
        跳过api_util.py;api.py,直接与test相连，并调用process_response（）输出日志
        """
        # response = requests.request(method, self.api_root_url + url, **kwargs)
        # return process_response(response)

    def request_log(self, url, method, **kwargs):
        # 日志打印
        data = dict(**kwargs).get('data')
        json_data = dict(**kwargs).get('json')
        params = dict(**kwargs).get('params')
        headers = dict(**kwargs).get('headers')

        logger.info("\n接口请求的地址>>>{}".format(self.api_root_url + url))
        logger.info("\n接口请求的方法>>>{}".format(method))
        if json_data is not None:
            logger.info("\n接口请求的json参数>>>\n{}".format(json.dumps(json_data, indent=2)))
        if data is not None:
            logger.info("\n接口请求的data参数>>>\n{}".format(json.dumps(data, indent=2)))
        if params is not None:
            logger.info("\n接口请求的params参数>>>\n{}".format(json.dumps(params, indent=2)))
        if headers is not None:
            logger.info("\n接口请求的headers参数>>>\n{}".format(json.dumps(headers, indent=2)))

API = RestClient()

